const Goods = require("../model/goods.model")

class GoodsServer {
  // 查找商品id是否存在
  async getGoodsId(id) {
    console.log(id)
    const res = await Goods.findOne({
      attributes:['id','goods_num'],
      where:{id:id}
    })
    return res
  }

  // 写入商品
  async createGoods(goods) {
    const res = await Goods.create(goods)
    return res.dataValues
  }

  // 修改商品
  async updateById({
    id,
    goods_name,
    goods_price,
    goods_num,
    goods_img
  }) {
    const whereOpt = {
      id
    }
    const newGoods = {}


    goods_name && Object.assign(newGoods, {
      goods_name
    })
    goods_price && Object.assign(newGoods, {
      goods_price
    })
    goods_num && Object.assign(newGoods, {
      goods_num
    })
    goods_img && Object.assign(newGoods, {
      goods_img
    })
    console.log("newGoods", newGoods)
    const res = await Goods.update(
      newGoods, {
        where: whereOpt
      })
    console.log(res)
    return res[0] > 0
  }

  // 下架商品
  async removeGoods(id) {
    const res = await Goods.destroy({
      where: {
        id
      }
    })
    return res
  }

  // 上架商品
  async restoreGoods(id) {
    const res = await Goods.restore({
      where: {
        id
      }
    })
    return res
  }

  // 商品列表
  async findGoods(pageNum, pageSize) {

    /*
    sql 原生的语句
     SELECT count(*) FROM zd_goods where deleteAt is null;
    */

    /*     const count = await Goods.count()
        console.log(count)
        const offset = (pageNum  - 1) * pageSize;
        const limit = pageSize*1
        const res = await Goods.findAll({offset,limit}) */
    const offset = (pageNum - 1) * pageSize;
    const limit = pageSize * 1
    const {
      count,
      rows
    } = await Goods.findAndCountAll({
      offset,
      limit
    })
    console.log(rows)
    return {
      pageNum,
      pageSize,
      total: count,
      list: rows
    }
  }

}

module.exports = new GoodsServer()
